﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Web;

namespace kindly
{
    public class DomainRedirectorModule : IHttpModule
    {
        const string FromHostName = "kindly.cz";
        const string ToHostName = "www.kindly.cz";

        public void Init(HttpApplication app)
        {
            app.BeginRequest += new EventHandler(app_BeginRequest);
        }

        protected void app_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            Uri currentUri = app.Request.Url;

            if (currentUri.Host == FromHostName)
            {
                Uri redirectToUri = new Uri(new Uri("http://" + ToHostName), currentUri.PathAndQuery);

                RedirectPermanently(app.Response, redirectToUri.ToString());
            }
        }

        public static void RedirectPermanently(HttpResponse response, string location)
        {
            // Permanent redirection
            response.Status = "301 Moved Permanently";
            response.AddHeader("Location", location);
            response.Flush();
            response.End();
        }

        public void Dispose()
        {
        }
    }
}